//
//  WXPWebLivenessVC.m
//  MexicoLoan
//
//  Created by wxp on 2025/4/14.
//
//

#import "WXPWebLivenessVC.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>

@interface WXPWebLivenessVC ()<UINavigationControllerDelegate,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIImagePickerControllerDelegate>

@property (nonatomic, strong) WKWebView * wkWebView;
@property (nonatomic, strong) WKUserContentController * userContentController;
@property (nonatomic, assign) BOOL hasPopped;
@property (nonatomic, strong) UIImage * resultImage;
@property (nonatomic,   copy) NSString * livenessId;

@end

@implementation WXPWebLivenessVC

#pragma mark - lazy
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.allowsInlineMediaPlayback = YES;
        WKPreferences *preferences = [WKPreferences new];
        // wkWebview支持window.open
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        wkWebConfig.preferences = preferences;
        // WKUserContentController *userContentController = [[WKUserContentController alloc]init];
        wkWebConfig.userContentController = self.userContentController;
        
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) configuration:wkWebConfig];
        _wkWebView.backgroundColor = [UIColor whiteColor];
        _wkWebView.multipleTouchEnabled = YES;
        _wkWebView.userInteractionEnabled = YES;
        _wkWebView.scrollView.scrollEnabled = YES;
        _wkWebView.contentMode = UIViewContentModeScaleAspectFit;
        _wkWebView.UIDelegate = self;
        _wkWebView.navigationDelegate = self;
    }
    return _wkWebView;
}

- (WKUserContentController *)userContentController
{
    if (_userContentController == nil) {
        _userContentController = [WKUserContentController new];
        [_userContentController addScriptMessageHandler:self name:@"setLivenessResult"];
    }
    return  _userContentController;
}




#pragma mark - viewDidLoad
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.userContentController removeScriptMessageHandlerForName:@"setLivenessResult"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.wkWebView];
    
    [self requestCloudunSdkAuthInfo];
}

- (void)dealloc {
    [self.userContentController removeScriptMessageHandlerForName:@"setLivenessResult"];
}


- (void)requestCloudunSdkAuthInfo {
    [RequestApi requestCloudunSdkAuthInfoWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        NSLog(@" --- 获取cloudun sdk授权信息 --- :%@",response);
        
        NSString * partnerCode = [response stringValueForKey:KEY_partnerCode];
        NSString * timestamp = [response stringValueForKey:KEY_timestamp];
        NSString * token = [response stringValueForKey:KEY_token];
        NSString * userID = [GlobalMethod getDeviceNo];
        NSString * urlString = @"";
        
#if DEBUG
        urlString = [NSString stringWithFormat:@"https://testh5.liveness.goodproduct.tech/resource/mxHld/?device=ios-app&language=es&partner-code=%@&timestamp=%@&token=%@&user_id=%@",partnerCode,timestamp,token,userID];
#else
        urlString = [NSString stringWithFormat:@"https://datacenter.haovili.com/resource/mxHld/?device=ios-app&language=es&partner-code=%@&timestamp=%@&token=%@&user_id=%@",partnerCode,timestamp,token,userID];
#endif
        
        // 加载 URL
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest * request = [NSURLRequest requestWithURL:url];
        
        
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 在后台线程中执行 startRunning 方法
            
            // 切换到主线程更新 UI
            dispatch_async(dispatch_get_main_queue(), ^{
                // 在主线程中更新 UI，例如隐藏 loadingView
                [self.wkWebView loadRequest:request];
                // 打点
                [GlobalMethod hitPointWithPageName:KEY_VerifyFacial action:KEY_H5_Liveness_Start extInfo:nil];
            });
        });
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}


// 获取权限
- (void)webView:(WKWebView *)webView
requestMediaCapturePermissionForOrigin:(WKSecurityOrigin *)origin
initiatedByFrame:(WKFrameInfo *)frame type:(WKMediaCaptureType)type
decisionHandler:(void (^)(WKPermissionDecision decision))decisionHandler
API_AVAILABLE(ios(15.0))
{
    decisionHandler(WKPermissionDecisionGrant);
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"setLivenessResult"]) {
        // 此时返回的body里包含了解析结果
        NSLog(@"返回结果了%@", message.body);

        if ([message.body isKindOfClass:[NSDictionary class]]) {
            NSDictionary *param = [NSDictionary dictionaryWithDictionary:message.body];
            
            NSDictionary *parmaResultDict = [GlobalMethod exchangeStringToDic:param[@"data"]];
            NSInteger code =  [[parmaResultDict numberValueForKey:@"code"] integerValue];
            if (code == 200) {
                // 检测成功
                NSString *livenessId = parmaResultDict[@"livenessId"];
                NSString *liveimg = parmaResultDict[@"img"];
                // 将 Base64 字符串转为 NSData
                NSData *imageData = [[NSData alloc] initWithBase64EncodedString:liveimg options:NSDataBase64DecodingIgnoreUnknownCharacters];
                // 将 NSData 转为 UIImage
                self.resultImage = [UIImage imageWithData:imageData];
                
                // SDK 活体预处理
                [self requestSDKPreLivenessWithLivenessId:livenessId];
            } else {
                // 检测失败
                // 如果sdk返回失败或者用户点击返回（左上角返回和物理返回都算）:则需要调用一次切换活体渠道接口，否则活体方式不会轮询
                if (self.hasPopped == false) {
                    self.hasPopped = true;
                    if(self.blockUploadFail){
                        self.blockUploadFail(code==401?@"Back":[parmaResultDict stringValueForKey:@"message"]);
                    }
                    // 切换活体渠道
                    [self changeLiveChanelIsPop:true];
                }
            }
        }
    }
    else if ([message.name isEqualToString:@"cameraAccess"]) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *vc = [[UIImagePickerController alloc] init];
            vc.delegate = self;
            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            vc.sourceType = UIImagePickerControllerSourceTypeCamera;
            vc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            [self presentViewController:vc animated:NO completion:nil];
        } else {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                        if (granted) {
                            UIImagePickerController *vc = [[UIImagePickerController alloc] init];
                            vc.delegate = self;
                            vc.sourceType = UIImagePickerControllerSourceTypeCamera;
                            vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                            vc.cameraDevice = UIImagePickerControllerCameraDeviceFront;

                            [self presentViewController:vc animated:NO completion:nil];
                        }
            }];
        }
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *captureImage = info[UIImagePickerControllerOriginalImage];
    
    UIImage * compressImage = [self compressImageSizetoByte:100 * 1024 image:captureImage];
    NSData *imageData = UIImageJPEGRepresentation(compressImage, 1.0);
    NSString *encodeString = [imageData base64Encoding];
    NSString *jscode = [NSString stringWithFormat:@"getImageBase64('%@');", encodeString];
//    NSString *jscode = [NSString stringWithFormat:@"getImageBase64();"];

    [self.wkWebView evaluateJavaScript:jscode completionHandler:nil];
    [picker dismissViewControllerAnimated:NO completion:^{
        [self.wkWebView evaluateJavaScript:@"document.body.innerHTML" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
            
//            [self reloadWebview];
        }];
    }];
}

- (UIImage *)compressImageSizetoByte:(NSUInteger)maxLength image:(UIImage *)image {
    CGFloat compression = 1.0;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    
    if (data.length < maxLength) {
        return [UIImage imageWithData:data];
    }
    
    CGFloat max = 1.0;
    CGFloat min = 0.0;
    
    for (int i = 0; i < 6; i++) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    if (data.length < maxLength) {
        return [UIImage imageWithData:data];
    }
    
    // 如果 JPEG 压缩不够，再尝试 PNG 压缩
    UIImage *resultImage = [UIImage imageWithData:data];
    if (resultImage) {
        data = UIImagePNGRepresentation(resultImage);
        if (data.length < maxLength) {
            return [UIImage imageWithData:data];
        }
    }
    
    // 如果 PNG 压缩还不够，就调整图片大小
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // 使用 sqrt 保持纵横比
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}

// SDK 活体预处理
- (void)requestSDKPreLivenessWithLivenessId:(NSString *)livenessId{
    self.livenessId = livenessId;
    [RequestApi requestPreLivenessWithLivenessId:livenessId delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [self requestOSSUploadLive];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [GlobalMethod showAlert:@"SDK 活体预处理接口 请求失败了"];
        if(self.blockUploadFail){
            self.blockUploadFail(errorStr);
        }
        // 切换活体渠道
        [self changeLiveChanelIsPop:true];
    }];
}

// 活体照片识别
- (void)requestOSSUploadLive{
    [self showLoadingView];
    [RequestApi requestAuthLiveWithImage:self.resultImage phone:self.phone livenChannelEnum:KEY_CLOUDUN_H5_V3 liveTypeEnum: self.liveTypeEnum delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        // NSLog(@" ------ %@",response);
        if([[response stringValueForKey:RESPONSE_CODE] intValue] == [RESPONSE_CODE_200 intValue]){
            // 成功
            NSDictionary * data = [response dictionaryValueForKey:RESPONSE_DATA];
            if(self.blockUploadSuccess){
                self.blockUploadSuccess([data stringValueForKey:KEY_url], [data stringValueForKey:KEY_photoName], self.livenessId);
            }
        }else{
            // 失败
            if(self.blockUploadFail){
                self.blockUploadFail([response stringValueForKey:RESPONSE_MESSAGE]);
            }
            // 切换活体渠道
            [self changeLiveChanelIsPop:false];
        }
        [self.loadingView hideLoading];
        [Global_Nav popViewControllerAnimated:true];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        [GlobalMethod showAlert:@"活体照片识别接口 请求失败了"];
        // 失败
        if(self.blockUploadFail){
            self.blockUploadFail(errorStr);
        }
        // 切换活体渠道
        [self changeLiveChanelIsPop:false];
        [self.loadingView hideLoading];
        [Global_Nav popViewControllerAnimated:true];
    }];
}

// 切换活体渠道接口
- (void)changeLiveChanelIsPop:(BOOL)isPop{
    [RequestApi requestChangeLiveChanelWithPhone:isStr(self.phone)?self.phone:@"" delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        if (isPop) {
            [Global_Nav popViewControllerAnimated:true];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

@end
